package com.ifish.leetcode.problem.algorithm;

import com.ifish.leetcode.problem.BaseLeetCodeProblem;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by iFish on 2017/7/9.
 */


//Reverse digits of an integer.
//
//        Example1: x = 123, return 321
//        Example2: x = -123, return -321
//
//        click to show spoilers.
//
//        Have you thought about this?
//        Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
//
//        If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
//
//        Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
//
//        For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
//
//        Note:
//        The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

public class _0007 extends BaseLeetCodeProblem {
    @Override
    public String title() {
        return "Reverse Integer";
    }

    @Override
    public void run() {
        super.run();

        int result = reverse(1563847412);
        printResult(result);
    }

    public int reverse(int x) {
        int result = 0;
        List<Integer> temp = new ArrayList<>();
        while (x != 0) {
            int d = x % 10;
            temp.add(d);
            x = x / 10;
        }
        try {
            for (int i = 0; i < temp.size(); i++) {
                // 溢出判断
                int plus = safeValue(temp.get(i) * multiple(10, temp.size() - i - 1));
                result = safeAdd(result, plus);
            }
            return result;
        } catch (Exception e) {
            return 0;
        }
    }

    private long multiple(int base, int multi) {
        long result = 1;
        for (int i = 0; i < multi; i++) {
            result *= base;
        }
        return result;
    }

    private int safeValue(long val) throws Exception {
        if (val > Integer.MAX_VALUE || val < Integer.MIN_VALUE) {
            throw new Exception();
        }
        return (int)val;
    }

    private int safeAdd(long a, long b) throws Exception {
        long val = a + b;
        if (val > Integer.MAX_VALUE || val < Integer.MIN_VALUE) {
            throw new Exception();
        }
        return (int)val;
    }
}
